<template>
  <!-- <yd-sendcode-button
    :size="size"
    :type="type"
    :action-type="actionType"
    :disabled="start"
    :class="start ? 'btn-disabled' : ''"
    :style="{backgroundColor: bgcolor, color: color}"
  >{{tmpStr}}</yd-sendcode-button>-->

  <button class="count-down">{{tmpStr}}</button>
</template>

<script>
import cookies from 'js-cookie'
export default {
  data() {
    return {
      tmpStr: this.initStr,
      timer: null,
      start: false,
      runSecond: this.second,
      lastSecond: 0
    };
  },
  props: {
    initStr: {
      type: String,
      default: "开始留观"
    },
    second: {
      default: 60 * 30,
      validator(val) {
        return /^\d*$/.test(val);
      }
    },
    runStr: {
      type: String,
      default: "{%s}秒后重新获取"
    },
    resetStr: {
      type: String,
      default: "重新获取验证码"
    },
    value: {
      type: Boolean,
      default: false
    },
    storageKey: {
      type: String
    }
  },
  methods: {
    run() {
      let lastSecond = this.lastSecond;
      let second = lastSecond ? lastSecond : this.runSecond;
      if (this.storageKey) {
        const runSecond = new Date().getTime() + second * 1000;
        // window.sessionStorage.setItem(this.storageKey, runSecond);
        cookies.set(this.storageKey, runSecond)
      }
      if (!lastSecond) {
        this.tmpStr = this.getStr(second);
      }
      this.timer = setInterval(() => {
        second--;
        this.tmpStr = this.getStr(second);
        second <= 0 && this.timeout();
      }, 1000);
    },
    timeout() {
      this.tmpStr = this.resetStr;
      this.start = false;
      this.$emit("input", false);
      clearInterval(this.timer);
    },
    getStr(second) {
      //   return this.runStr.replace(/\{([^{]*?)%s(.*?)\}/g, second);
      const min = this.format(~~(second / 60));
      const sec = this.format(second % 60);
      return `${min}分${sec}秒`;
    },
    format(val) {
      return val < 10 ? `0${val}` : val;
    }
  },
  watch: {
    value(val) {
      this.start = val;
      if (!val) {
        clearInterval(this.timer);
        this.tmpStr = this.initStr;
        if (this.storageKey) {
        //   window.sessionStorage.removeItem(this.storageKey);
          cookies.remove(this.storageKey)
          this.lastSecond = 0;
        }
      } else {
        this.run();
      }
    }
  },
  created() {
    // const lastSecond = ~~(
    //   (window.sessionStorage.getItem(this.storageKey) - new Date().getTime()) /
    //   1000
    // );
    const lastSecond = ~~(
      (cookies.get(this.storageKey) - new Date().getTime()) /
      1000
    );
    if (lastSecond > 0 && this.storageKey) {
      this.$emit("input", true);
      this.tmpStr = this.getStr(lastSecond);
      this.lastSecond = lastSecond;
    }
  },
  beforeDestroy() {
    !this.storageKey && this.timeout();
  }
};
</script>
<style lang='scss' scoped>
.count-down {
  display: block;
  width: 100%;
}
</style>
